//完成与权限操作相关的业务
const permModel = require('../model/permModel.js');
const roleModel = require('../model/roleModel.js');
const url = require('url');
//获取角色对应的权限列表
module.exports.getPermByRid = async (req,res) =>{
	//1.从token中获取角色id
	let {rid} = req.data;
	console.log(rid);
	//2.根据角色id把角色对应的权限，从所有权限中删选出来
	//获得所有权限
	let result = await permModel.getAllPerm();
	if(result.length > 0){
		//获得角色的权限id列表
		let psids = await roleModel.getPsidsByRid(rid);
		let psidsArr = psids[0].ps_ids.split(',');
		let menuArr =  menuTree(rid,psidsArr,result);
		res.send({
			data: menuArr,
			meta:{
				msg:'权限获取成功',
				status: 200
			}
			
		})
	}else{
		res.send({
			meta: {
				msg: '权限获取失败',
				status: 402
			}
		})
	}
	
}
//生成二级权限菜单树
/**
 * rid  角色id
 * psidsArr 角色对应权限id数组
 * result 所有的权限
 */
let menuTree = (rid,psidsArr,result) =>{
	//定义数组去装二级菜单树
	let menuTArr = [];
	//生成一级菜单
	//遍历所有的权限，把角色拥有的一级权限过滤出，存到数组中
	for(i in result){
		let perm = result[i];
		//过滤出一级，就是ps_level==0
		if(perm.ps_level == 0){
			//判断角色权限id数组中，是否包含本次循环中的权限id,不包含就直接过滤掉
			if(rid != 0){
			   if( psidsArr.indexOf(perm.ps_id+'') < 0) continue;
			}
			menuTArr.push({
				"id": perm.ps_id,
				"authName": perm.ps_name,
				"path": perm.ps_api_path,
				"children": []
			})
		}
	}
	//生成二级权限菜单
	//遍历一级菜单数组，把一级菜单对应的二级菜单对应的添加进去
	for(i in menuTArr){
		let mta = menuTArr[i];
		//遍历所有权限，把二级权限菜单删选出
		for( j in result){
			let perm = result[j];
			if( perm.ps_level == 1 && mta.id == perm.ps_pid){
				if(rid != 0){
				   if( psidsArr.indexOf(perm.ps_id+'') < 0) continue;
				}
				mta.children.push({
					"id": perm.ps_id,
					"authName": perm.ps_name,
					"path": perm.ps_api_path,
					"children": []
				})
			}
		}
	}
	return menuTArr;
}
//
module.exports.getPermByPage = async (req,res) =>{
	let {query} = url.parse(req.url,true);
	let {pagenum,pagesize} = query;
	pagenum = parseInt(pagenum);
	pagesize = parseInt(pagesize);
	console.log(pagenum,pagesize)
	//获得权限表的总条数
	let count = await permModel.getPermCount();
	count = count[0].cou;
	let totalpage = Math.ceil(count/pagesize)
	//计算起始下标
	let offset = (pagenum-1)*pagesize;
	if(offset >= count){
		pagenum=1;
		offset=0;
	}
	//创建给占位符传值的数组
	let pageInfo = [offset,pagesize]
	let result = await permModel.getPermByPage(pageInfo)
	let perms = []
	for(i in result){
		let perm = result[i];
		perms.push({
            "id": perm.ps_id,
            "authName": perm.ps_name,
            "level": perm.ps_level,
            "pid": perm.id,
            "path": perm.ps_api_path
        })
	}
	res.send({
		data:{
			'totalpage':totalpage,
			'pagenum':pagenum,
			'total':count,
			'perms':perms
		},
		meta:{
			msg:'权限列表获取成功',
			status:200
		}
	})
}